//
//  BaseTopRightView.swift
//  GomroClient
//
//  Created by mac on 2020/4/9.
//  Copyright © 2020 cn.gomro.app. All rights reserved.
//

import UIKit

/** 公共右边搜索视图 */
class BaseTopRightView: UIView {

    var arrSearch:[[String:Any]]?{
        didSet{
            self.searchTableView.reloadData()
        }
    }
    
    lazy var isReload:Bool = false
    lazy var dicSelectValue = [String:String]()
    
    weak var delegate:BaseTopViewDelegate?
    weak var pViewController:UIViewController?
    
    
    //MARK: - override
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.initView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func updateConstraints() {
        
        self.labTitle.snp.makeConstraints { make in
            make.top.equalTo(K_APP_SAFETY_NAV_HEIGHT)
            make.left.right.equalTo(0)
            make.height.equalTo(44)
        }
        
        self.footView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.bottom.equalTo(-K_APP_SAFETY_HEIGHT)
            make.height.equalTo(60)
        }
        
        self.searchTableView.snp.makeConstraints { [weak self] make in
            guard let self = self else { return }
            make.top.equalTo(self.labTitle.snp.bottom)
            make.left.right.equalTo(0)
            make.bottom.equalTo(self.footView.snp.top)
        }
        
        self.btnClean.snp.makeConstraints {[unowned self] make in
            make.right.equalTo(-20)
            make.height.equalTo(self.labTitle.snp.height)
            make.top.equalTo(self.labTitle.snp.top)
            make.width.equalTo(44)
        }
        
        super.updateConstraints()
    }
    
    
    //MARK: - initView
    private func initView(){
        self.backgroundColor = K_APP_VIEWCONTROLLER_BACKGROUND_COLOR
        
        self.addSubview(self.labTitle)
        self.addSubview(self.searchTableView)
        self.addSubview(self.footView)
        self.addSubview(self.btnClean)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(notification:)), name: NSNotification.Name(rawValue: UIResponder.keyboardWillShowNotification.rawValue), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide(notification:)), name: NSNotification.Name(rawValue: UIResponder.keyboardWillHideNotification.rawValue), object: nil)

        setNeedsUpdateConstraints()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    //MARK: - 搜索
    @IBAction private func btnSearchAction(sender:UIButton?) {
        
//        if self.arrSearch == nil || self.arrSearch!.count <= 0 {
//            SVProgressHUD.showInfo(withStatus: "搜索信息不存在")
//            return
//        }
//
//        var tag = 0
//        var params = [String:Any]()
//
//        var strKey:String?,strValue:String?
//        var cell:DemandCreateTableViewCell?
//
//        for i in 0..<self.arrSearch!.count {
//            cell = self.searchTableView.cellForRow(at: IndexPath.init(row: i, section: 0)) as? DemandCreateTableViewCell
//
//            if cell != nil {
//                strKey = self.arrSearch![i][k_code] as? String
//                strValue = cell?.txtInfo.text
//
//                if self.dicSelectValue.keys.contains(strKey!) {
//                    strValue = self.dicSelectValue[strKey!]
//                }
//
//                params[strKey!] = strValue
//
//                if strValue != nil && strValue != "" {
//                    tag += 1
//                }
//            }
//        }
//
//        self.isReload = false
//        self.delegate?.baseTopViewDidSearchFor?(Paramas: params)
//        self.pViewController?.zh_popupController.dismiss()
    }
    
    
    //MARK: - dropDownListShow
    private func dropDownListShow(index:Int,
                                  section:Int,
                                  title:String?){
       guard var _title = title else { return }
       
       _title = _title.replacingOccurrences(of: "*", with: "")
       /*
       //MARK:时间
        if _title.contains("时间") || _title.contains("截止") {
         self.selectDateBoxView.boxTitle = _title
         self.selectDateBoxView.selectBoxFinish = { [weak self](strSelect:String?) in
             
             guard let self = self else { return }
             let _indexPath = IndexPath.init(row: index, section: section)
             guard let cell:DemandCreateTableViewCell = self.searchTableView.cellForRow(at: _indexPath) as? DemandCreateTableViewCell else { return }
             
             if strSelect != nil {
                 cell.txtInfo.text = strSelect
             }
             
             //还原状态
             self.animationRightEnd(sender: cell.btnRight)
         }
         self.selectDateBoxView.showBoxView()
      }
       else{
           switch _title {
           //MARK:订单状态
           case "订单状态":
               self.selectBoxView.boxTitle = _title
            
               //订单状态（0:全部,1:新建,2:待付款,3:已付款,4:退货,5:取消,6:已完成,7.已驳回）
               self.selectBoxView.dataValues = ["0","1","2","3","4","5","6","7",]
               self.selectBoxView.dataArr = ["全部","新建","待付款","已付款","退货","取消","已完成","已驳回"]
               
               self.selectBoxView.selectBoxFinish = { [weak self](strSelect:String?,strServerV:String?) in
                   
                   guard let self = self else { return }
                   let _indexPath = IndexPath.init(row: index, section: section)
                   guard let cell:DemandCreateTableViewCell = self.searchTableView.cellForRow(at: _indexPath) as? DemandCreateTableViewCell else { return }
                   
                   if strSelect != nil {
                       cell.txtInfo.text = strSelect
                    
                       let key = self.arrSearch != nil ? self.arrSearch!.first { return $0[k_title] as? String == _title }?[k_code] as? String ?? "statusCode" : "statusCode"
                       self.dicSelectValue[key] = strServerV ?? ""
                   }
                   
                   //还原状态
                   self.animationRightEnd(sender: cell.btnRight)
               }
               self.selectBoxView.showBoxView()
               break
               
           //MARK:开票申请状态
           case "开票申请状态":
               self.selectBoxView.boxTitle = _title
               self.selectBoxView.dataValues = ["ALL","NEW","APPROVING","RETURNED","DRAWER_CONFIRMING","RECEIVER_CONFIRMING","DONE","CANCEL"]
               self.selectBoxView.dataArr = ["全部","新建","待申请审批","已退回","待开票","待收票确认","已开票","已关闭"]
               
               self.selectBoxView.selectBoxFinish = { [weak self](strSelect:String?,strServerV:String?) in
                   
                   guard let self = self else { return }
                   let _indexPath = IndexPath.init(row: index, section: section)
                   guard let cell:DemandCreateTableViewCell = self.searchTableView.cellForRow(at: _indexPath) as? DemandCreateTableViewCell else { return }
                   
                   if strSelect != nil {
                       cell.txtInfo.text = strSelect
                       let key = self.arrSearch != nil ? self.arrSearch!.first { return $0[k_title] as? String == _title }?[k_code] as? String ?? "invoiceApplyStatus" : "invoiceApplyStatus"
                       self.dicSelectValue[key] = strServerV ?? ""
                   }
                   
                   //还原状态
                   self.animationRightEnd(sender: cell.btnRight)
               }
               self.selectBoxView.showBoxView()
               break
               
           //MARK:开票状态
           case "开票状态":
               self.selectBoxView.boxTitle = _title
               self.selectBoxView.dataValues = ["ALL","UNDO","DOING","DONE"]
               self.selectBoxView.dataArr = ["全部","未开票","开票中","已开票"]
               
               self.selectBoxView.selectBoxFinish = { [weak self](strSelect:String?,strServerV:String?) in
                   
                   guard let self = self else { return }
                   let _indexPath = IndexPath.init(row: index, section: section)
                   guard let cell:DemandCreateTableViewCell = self.searchTableView.cellForRow(at: _indexPath) as? DemandCreateTableViewCell else { return }
                   
                   if strSelect != nil {
                       cell.txtInfo.text = strSelect
                       let key = self.arrSearch != nil ? self.arrSearch!.first { return $0[k_title] as? String == _title }?[k_code] as? String ?? "invoiceStatus" : "invoiceStatus"
                       self.dicSelectValue[key] = strServerV ?? ""
                   }
                   
                   //还原状态
                   self.animationRightEnd(sender: cell.btnRight)
               }
               self.selectBoxView.showBoxView()
               break
               
           //MARK:发票状态
           case "发票状态":
               self.selectBoxView.boxTitle = _title
               self.selectBoxView.dataValues = ["ALL","UNDO","DOING","DONE"]
               self.selectBoxView.dataArr = ["全部","未开票","开票中","已开票"]
               
               self.selectBoxView.selectBoxFinish = { [weak self](strSelect:String?,strServerV:String?) in
                   
                   guard let self = self else { return }
                   let _indexPath = IndexPath.init(row: index, section: section)
                   guard let cell:DemandCreateTableViewCell = self.searchTableView.cellForRow(at: _indexPath) as? DemandCreateTableViewCell else { return }
                   
                   if strSelect != nil {
                       cell.txtInfo.text = strSelect
                       let key = self.arrSearch != nil ? self.arrSearch!.first { return $0[k_title] as? String == _title }?[k_code] as? String ?? "invoiceStatus" : "invoiceStatus"
                    self.dicSelectValue[key] = strServerV ?? ""
                   }
                   
                   //还原状态
                   self.animationRightEnd(sender: cell.btnRight)
               }
               self.selectBoxView.showBoxView()
               break
               
           //MARK:商品状态
           case "商品状态":
               self.selectBoxView.boxTitle = _title
               self.selectBoxView.dataValues = ["","NEW","SUBMIT","PAYED","PACKAGING","DELIVERED","TO_RETURN","RETURNING","REFUNDING","RETIRED","MIDDLEMAN","DONE","CLOSED","REFUND_APPLICATION","RETURNED","TO_REFUND"]
               self.selectBoxView.dataArr = ["全部","新建","待付款","待发货","出库中","已发货","待退货","退货中","退款中","已退货","客服已介入","已完成","已关闭","退款申请中","已退款","待退款"]
               
               self.selectBoxView.selectBoxFinish = { [weak self](strSelect:String?,strServerV:String?) in
                   
                   guard let self = self else { return }
                   let _indexPath = IndexPath.init(row: index, section: section)
                   guard let cell:DemandCreateTableViewCell = self.searchTableView.cellForRow(at: _indexPath) as? DemandCreateTableViewCell else { return }
                   
                   if strSelect != nil {
                       cell.txtInfo.text = strSelect
                       let key = self.arrSearch != nil ? self.arrSearch!.first { return $0[k_title] as? String == _title }?[k_code] as? String ?? "orderGoodsStatus" : "orderGoodsStatus"
                       self.dicSelectValue[key] = strServerV ?? ""
                   }
                   
                   //还原状态
                   self.animationRightEnd(sender: cell.btnRight)
               }
               self.selectBoxView.showBoxView()
               break
            
           //MARK:付款状态
           case "付款状态":
               self.selectBoxView.boxTitle = _title
               self.selectBoxView.dataValues = ["ALL","UNDO","DOING","DONE"]
               self.selectBoxView.dataArr = ["全部","未付款","付款中","已付款"]
               
               self.selectBoxView.selectBoxFinish = { [weak self](strSelect:String?,strServerV:String?) in
                   
                   guard let self = self else { return }
                   let _indexPath = IndexPath.init(row: index, section: section)
                   guard let cell:DemandCreateTableViewCell = self.searchTableView.cellForRow(at: _indexPath) as? DemandCreateTableViewCell else { return }
                   
                   if strSelect != nil {
                       cell.txtInfo.text = strSelect
                       let key = self.arrSearch != nil ? self.arrSearch!.first { return $0[k_title] as? String == _title }?[k_code] as? String ?? "paymentStatus" : "paymentStatus"
                       self.dicSelectValue[key] = strServerV ?? ""
                   }
                   
                   //还原状态
                   self.animationRightEnd(sender: cell.btnRight)
               }
               self.selectBoxView.showBoxView()
               break
             
           //MARK:对账状态
           case "对账状态":
               self.selectBoxView.boxTitle = _title
               self.selectBoxView.dataValues = ["ALL","UNDO","DOING","DONE","STOP"]
               self.selectBoxView.dataArr = ["全部","未对账","对账中","已对账","已关闭"]
               
               self.selectBoxView.selectBoxFinish = { [weak self](strSelect:String?,strServerV:String?) in
                   
                   guard let self = self else { return }
                   let _indexPath = IndexPath.init(row: index, section: section)
                   guard let cell:DemandCreateTableViewCell = self.searchTableView.cellForRow(at: _indexPath) as? DemandCreateTableViewCell else { return }
                   
                   if strSelect != nil {
                       cell.txtInfo.text = strSelect
                       let key = self.arrSearch != nil ? self.arrSearch!.first { return $0[k_title] as? String == _title }?[k_code] as? String ?? "reconciliationStatus" : "reconciliationStatus"
                       self.dicSelectValue[key] = strServerV ?? ""
                   }
                   
                   //还原状态
                   self.animationRightEnd(sender: cell.btnRight)
               }
               self.selectBoxView.showBoxView()
               break
            
            //MARK:澄清状态
            case "澄清状态":
                self.selectBoxView.boxTitle = _title
                /**
                 INQUIRY_GOODS_0_NEW 新建
                 INQUIRY_GOODS_1_APPROVE 审核中
                 INQUIRY_GOODS_2_APPROVE_NO 已退回
                 INQUIRY_GOODS_3_QUOTING 报价中
                 INQUIRY_GOODS_4_END 已结束
                 INQUIRY_GOODS_5_CLOSE 已关闭
                */
                self.selectBoxView.dataValues = ["INQUIRY_GOODS_0_NEW","INQUIRY_GOODS_1_APPROVE","INQUIRY_GOODS_2_APPROVE_NO","INQUIRY_GOODS_3_QUOTING","INQUIRY_GOODS_4_END","INQUIRY_GOODS_5_CLOSE"]
                self.selectBoxView.dataArr = ["新建","审核中","已退回","报价中","已结束","已关闭"]
                
                self.selectBoxView.selectBoxFinish = { [weak self](strSelect:String?,strServerV:String?) in
                    
                    guard let self = self else { return }
                    let _indexPath = IndexPath.init(row: index, section: section)
                    guard let cell:DemandCreateTableViewCell = self.searchTableView.cellForRow(at: _indexPath) as? DemandCreateTableViewCell else { return }
                    
                    if strSelect != nil {
                        cell.txtInfo.text = strSelect
                        let key = self.arrSearch != nil ? self.arrSearch!.first { return $0[k_title] as? String == _title }?[k_code] as? String ?? "reconciliationStatus" : "reconciliationStatus"
                        self.dicSelectValue[key] = strServerV ?? ""
                    }
                    
                    //还原状态
                    self.animationRightEnd(sender: cell.btnRight)
                }
                self.selectBoxView.showBoxView()
                break
               
           default:
               break
           }
       }
 */
   }
       
    private func animationRightEnd(sender:UIButton) {
        UIView.animate(withDuration: 0.35) {
            sender.imageView?.transform = CGAffineTransform.init(rotationAngle: 0)
        }
    }
       
    private func animationRight(sender:UIButton){
        UIView.animate(withDuration: 0.35, animations: {
            sender.imageView?.transform = CGAffineTransform.init(rotationAngle: CGFloat(Double.pi * 0.5))
        })
    }
    
    
    
    //MARK: - lazy load
    lazy var labTitle:YYLabel = {
        let _l = BaseView.createLable(rect: CGRect.zero,
                             text: "筛选",
                             textColor: UIColor.init().colorFromHexString(hex: "#333333"),
                             font: UIFont.boldSystemFont(ofSize: 16),
                             backgroundColor: UIColor.clear)
        _l.textAlignment = .center
        return _l
    }()
    
    lazy var searchTableView:UITableView = {
        let _tb = UITableView.init(frame: CGRect.zero,
                                   style: UITableView.Style.plain)
        
        _tb.backgroundColor = K_APP_VIEWCONTROLLER_BACKGROUND_COLOR
        _tb.isScrollEnabled = true
        
        _tb.showsVerticalScrollIndicator = false
        _tb.showsHorizontalScrollIndicator = false
        
        //适配平板
        _tb.cellLayoutMarginsFollowReadableWidth = false
        
        //分割线
        _tb.separatorStyle = .singleLine
        _tb.separatorColor = K_APP_SPLIT_LINE_COLOR
        
        //行选中
        _tb.allowsSelection = true
        _tb.allowsMultipleSelection = false
        
        //表头、表尾
        _tb.tableHeaderView = UIView.init(frame: .zero)
        _tb.tableFooterView = UIView.init(frame: .zero)
        
        _tb.delegate = self
        _tb.dataSource = self
        
        //防止顶部空白
        if #available(iOS 11.0, *) {
            _tb.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never
        }
        
        //注册
        //_tb.register(DemandCreateTableViewCell.classForCoder(),
                     //forCellReuseIdentifier: DemandCreateTableViewCell.cell_identify)
    
        return _tb
    }()
    
    private lazy var footView:UIView = {
        let _v = BaseView.createView(rect: CGRect.zero,
                            backgroundColor: UIColor.clear,
                            isRadius: false,
                            cornerRadius: 0,
                            andBorder: 0,
                            andBorderColor: nil)
        
        let _btn = BaseView.createBtn(rect: CGRect.zero,
                             strTitle: "确定",
                             titleColor: UIColor.white,
                             txtFont: UIFont.systemFont(ofSize: 16, weight: .medium),
                             image: nil,
                             backgroundColor: K_APP_TINT_COLOR,
                             borderColor: nil,
                             cornerRadius: 5,
                             isRadius: true,
                             backgroundImage: nil,
                             borderWidth: 0)
        
        _btn.addTarget(self, action: #selector(btnSearchAction(sender:)), for: .touchUpInside)
        
        _v.addSubview(_btn)
        _btn.snp.makeConstraints { make in
            make.height.equalTo(40)
            make.left.equalTo(13)
            make.right.equalTo(-13)
            make.top.equalTo(10)
        }
        
        return _v
    }()
    
    private lazy var selectDateBoxView:DateBoxView = {
        return DateBoxView.init(frame: UIScreen.main.bounds)
    }()
   
    private lazy var selectBoxView:SelectBoxView = {
       let _s = SelectBoxView.init(frame: UIScreen.main.bounds)
       
       return _s
   }()
    
   private lazy var btnClean:UIButton = {
        let _b = BaseView.createBtn(rect: CGRect.zero,
                           strTitle: "重置",
                           titleColor: UIColor.gray,
                           txtFont: UIFont.systemFont(ofSize: 15),
                           image: nil,
                           backgroundColor: nil,
                           borderColor: nil,
                           cornerRadius: nil,
                           isRadius: false,
                           backgroundImage: nil,
                           borderWidth: nil)
        
        _b.rac_signal(for: .touchUpInside)?.subscribeNext({[weak self] (input:Any?) in
            guard let self = self else { return }
        
            self.isReload = true
            self.delegate?.baseTopViewCancleSearch?(isClean: true)
            self.pViewController?.zh_popupController.dismiss()
        })
        
        return _b
    }()
    
}


//MARK: -
extension BaseTopRightView {
    
    @objc func keyboardWillChangeFrame(notification:Notification) {
        
        //取出键盘动画的时间(根据userInfo的key----UIKeyboardAnimationDurationUserInfoKey)
        //notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval
        
        //取得键盘最后的frame(根据userInfo的key----UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";)
        //notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        
        self.frame.origin.y = 2 * K_APP_NAVIGATION_BAR_HEIGHT
    }
    
    @objc func keyboardDidHide(notification:Notification){
        self.frame.origin.y = 0
    }
}


//MARK: - UITableViewDelegate、UITabelViewDataSource
extension BaseTopRightView : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    //MARK:组头、组尾
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }

    //MARK:列
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.arrSearch != nil {
            return self.arrSearch!.count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 0.0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        autoreleasepool {
            return UITableViewCell.init()
//            var cell:DemandCreateTableViewCell? = tableView.dequeueReusableCell(withIdentifier: DemandCreateTableViewCell.cell_identify) as? DemandCreateTableViewCell
//            if cell == nil {
//               cell = DemandCreateTableViewCell.init(style: .default, reuseIdentifier: DemandCreateTableViewCell.cell_identify)
//            }
//
//            cell?.tag = indexPath.section
//            cell?.txtInfo.delegate = self
//            cell?.txtInfo.textAlignment = .right
//
//            cell?.txtInfo.tag = indexPath.row
//            cell?.btnRight.tag = indexPath.row
//
//            DispatchQueue.main.async {
//                cell?.labTitle.snp.remakeConstraints({ make in
//                    make.width.equalTo(125)
//                    make.left.equalTo(13)
//                    make.top.bottom.equalTo(0)
//                })
//            }
//
//            cell?.selectActionBlock = {[weak self] (_index:Int,_section:Int,_title:String?,_sender:UIButton) in
//                guard let self = self else { return }
//
//                self.dropDownListShow(index: _index, section: _section, title: _title)
//                self.animationRight(sender: _sender)
//            }
//
//            if self.arrSearch != nil && self.arrSearch!.count > indexPath.row {
//                let dicTemp = self.arrSearch![indexPath.row]
//                cell?.cellBindValueFor(Data: dicTemp,
//                                       andModel: NSNull.self)
//            }
//
//            return cell!
//        }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        defer {
//            tableView.deselectRow(at: indexPath, animated: true)
//        }
        
//        guard let cell = tableView.cellForRow(at: indexPath) as? DemandCreateTableViewCell,cell.btnRight.isHidden == false else { return }
//        cell.selectActionBlock?(cell.btnRight.tag,
//                                cell.btnRight.superview?.superview?.tag ?? 0,
//                                cell.labTitle.text,
//                                cell.btnRight)

    }
}


//MARK: - UITextFilesDelegate
extension BaseTopRightView : UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        // [S] 禁止用户切换键盘为Emoji表情
        if textField.isFirstResponder {
            if textField.textInputMode?.primaryLanguage == "emoji" || textField.textInputMode?.primaryLanguage == nil {
                return false
            }
        }
        // [E] 禁止用户切换键盘为Emoji表情

        let length = textField.text?.count ?? 0
        let strLength = string.lengthOfBytes(using: String.Encoding.utf8)

        //单号长度限制
        if textField.tag == 0 && strLength != 0 && length >= 8 {
            return false
        }
        else if textField.tag == 1 && textField.placeholder != nil && textField.placeholder!.hasSuffix("号") && length >= 8 {
            return false
        }
        
        return true
    }
}
